//
//  FuelMgr.m
//  carcareIOS
//
//  Created by ileo on 16/4/12.
//  Copyright © 2016年 chezheng. All rights reserved.
//

#import "FuelMgr.h"
#import "DateModel.h"
#import "CalendarMgr.h"
#import "AIUserInfo.h"
#import "NetFuel.h"
#import "MapHelper.h"
#import "UserHelper.h"

NSString * const FUEL_UPDATE = @"FUEL_UPDATE";

@interface FuelMgr ()

@property (nonatomic, strong) NSMutableDictionary *fuelInfos;

@property (nonatomic, strong) DateModel *leftmostMonth;//最左边月份
@property (nonatomic, strong) DateModel *rightmostMonth;//最右边月份

@property (nonatomic, strong) NSMutableArray *monthModels;

#pragma mark - default
@property (nonatomic, copy) NSDictionary *defaultInfo;

@end

@implementation FuelMgr

IMP_SINGLETON

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(instancetype)init{
    self = [super init];
    
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clear) name:USER_LOGIN object:nil];
        [self initFuelRecords];
        [self initFuelDefault];
    }
    
    return self;
}

#pragma mark - init

-(void)clear{
    [self.fuelInfos removeAllObjects];
    [self.monthModels removeAllObjects];

    [self initFuelRecords];
    [self initFuelDefault];
}

- (void)initFuelRecords {
    NSInteger max = 11;
    NSInteger start = -5;
    for (int i = 0; i < max; i++) {
        NSInteger sub = i + start;
        if (sub < 0) {
            [self.monthModels addObject:[CALENDARMGR monthBeforeDateModel:CALENDARMGR.today months:-sub]];
        }else if (sub == 0) {
            [self.monthModels addObject:CALENDARMGR.today];
        }else{
            [self.monthModels addObject:[CALENDARMGR monthAfterDateModel:CALENDARMGR.today month:sub]];
        }
    }
    self.currentMonth = CALENDARMGR.today;
}

- (void)initFuelDefault {
    __weak __typeof(self) wself = self;
    [[NetFuel getFuelDefaultSettingInfo] requestSuccess:^(id JSON) {
        wself.defaultInfo = JSON[@"Oil"];
        [wself initChoiceFuelInfo];
    }];
}

-(void)initChoiceFuelInfo{
    
    self.choiceProvince = self.defaultInfo[@"city"];
    self.choiceCity = self.defaultInfo[@"commonCity"];
    self.choiceFuelPriceModel = [[FuelPriceModel alloc] initWithDic:self.defaultInfo];
    self.hasDefault = [self.choiceCity isNotNil];
    
    if (![self.choiceCity isNotNil] || ![self.choiceProvince isNotNil]) {
        __weak __typeof(self) wself = self;
        [MapHelper addressFromReGeocode:MAPMGR.currentReGeocode result:^(NSString *province, NSString *city, NSString *district) {
            wself.choiceProvince = [[province componentsSeparatedByString:@"省"][0] componentsSeparatedByString:@"市"][0];
            wself.choiceCity = [city componentsSeparatedByString:@"市"][0];
        }];
    }
}

#pragma mark -

-(void)addLastMonthCallback:(void (^)(BOOL))callback{
    DateModel *model = [CALENDARMGR monthBeforeDateModel:self.monthModels.firstObject];
    if (![CALENDARMGR dateModel:model monthIsBeforeThanDateModel:self.leftmostMonth]) {
        [self.monthModels insertObject:model atIndex:0];
        if (callback) {
            callback(YES);
        }
    }else{
        if (callback) {
            callback(NO);
        }
    }
}

-(void)addNextMonthCallback:(void (^)(BOOL))callback{
    DateModel *model = [CALENDARMGR monthAfterDateModel:self.monthModels.lastObject];
    if (![CALENDARMGR dateModel:self.rightmostMonth monthIsBeforeThanDateModel:model]) {
        [self.monthModels addObject:model];
        if (callback) {
            callback(YES);
        }
    }else{
        if (callback) {
            callback(NO);
        }
    }
}

-(FuelMonthModel *)fuelModelWithMonthModel:(DateModel *)dateModel{
    
    if ([CALENDARMGR dateModel:dateModel monthIsBeforeThanDateModel:USERINFO.bindingDay] ||
        [CALENDARMGR dateModel:CALENDARMGR.today monthIsBeforeThanDateModel:dateModel]) {
        FuelMonthModel *model = [[FuelMonthModel alloc] init];
        model.monthModel = dateModel;
        return model;
    }
    NSString *key = [NSString stringWithFormat:@"%zd-%02zd",dateModel.year,dateModel.month];
    
    if (!self.fuelInfos[key]) {
        __weak __typeof(self) wself = self;
        [[NetFuel getFuelRecordsWithMonth:key] requestSuccess:^(id JSON) {
            NSArray *tmp = JSON[@"fuelLog"];
            NSMutableArray *arr = [NSMutableArray arrayWithCapacity:tmp.count];
            NSInteger max = tmp.count;
            CGFloat cost = 0;
            CGFloat fuels = 0;
            for (int i = 0; i < max; i++) {
                FuelRecordModel *record = [[FuelRecordModel alloc] initWithDic:tmp[i]];
                cost += record.totalPrice;
                fuels += record.fuelVol;
                [arr addObject:record];
            }
//            [arr sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
//                NSString *str1 = ((FuelRecordModel *)obj1).CDT;
//                NSString *str2 = ((FuelRecordModel *)obj2).CDT;
//                return [str2 compare:str1 options:NSNumericSearch];
//            }];
            FuelMonthModel *model = [[FuelMonthModel alloc] init];
            model.totalTimes = max;
            model.totalCost = cost;
            model.totalFuelL = fuels;
            model.monthModel = dateModel;
            model.fuelRecords = arr;
            wself.fuelInfos[key] = model;
            wself.maxFuelCost = MAX(wself.maxFuelCost, cost);
            [[NSNotificationCenter defaultCenter] postNotificationName:FUEL_UPDATE object:nil];
            
        }];
        
        FuelMonthModel *model = [[FuelMonthModel alloc] init];
        model.monthModel = dateModel;
        return model;

    }
    return self.fuelInfos[key];
}

-(void)getRecentlyFuelDate:(void (^)(NSString *))callBack{
    [[NetFuel getRecentlyFuel] requestSuccess:^(id JSON) {
        if (callBack) callBack([CALENDARMGR dateStrWithDate:[CALENDARMGR dateWithStr:JSON[@"latestDate"] format:yyyy_MM_dd_HH_mm_ss] format:@"MM/dd"]);
    }];
}

-(NSInteger)indexWithDateModel:(DateModel *)dateModel{
    return [self.monthModels indexOfObject:dateModel];
}

-(void)addNewFuelRecord:(FuelRecordModel *)model succ:(void (^)())succ fail:(void (^)())fail{
    __weak __typeof(self) wself = self;
    [[NetFuel addNewFuelRecordWithInfo:model.uploadDic] requestSuccess:^(id JSON) {
        wself.fuelInfos[model.monthKey] = nil;
        if (succ) succ();
    } failure:^(id JSON) {
        [AlertMgr showShortWarnTextTips:@[JSON[@"errMsg"]]];
        if (fail) fail();
    }];
}

-(void)updateFuelRecord:(FuelRecordModel *)model succ:(void (^)())succ fail:(void (^)())fail{
    __weak __typeof(self) wself = self;
    [[NetFuel updateFuelRecordWithInfo:model.uploadDic] requestSuccess:^(id JSON) {
        wself.fuelInfos[model.monthKey] = nil;
        if (succ) succ();
    } failure:^(id JSON) {
        [AlertMgr showShortWarnTextTips:@[JSON[@"errMsg"]]];
        if (fail) fail();
    }];
}

-(void)deleteFuelRecord:(FuelRecordModel *)model succ:(void (^)())succ fail:(void (^)())fail{
    __weak __typeof(self) wself = self;
    [[NetFuel delFuelRecordWithID:model.ID] requestSuccess:^(id JSON) {
        wself.fuelInfos[model.monthKey] = nil;
        if (succ) succ();
    } failure:^(id JSON) {
        if (fail) fail();
    }];
}

-(void)readNewFuelRecord:(FuelRecordModel *)model{
    __weak __typeof(self) wself = self;
    [[NetFuel hadReadNewFuelRecordWithID:model.ID] requestSuccess:^(id JSON) {
        wself.fuelInfos[model.monthKey] = nil;
    }];
}

#pragma mark - 
-(void)resetDefaultSuccess:(void (^)())success fail:(void (^)())fail{
    __weak __typeof(self) wself = self;
    if ([self.choiceCity isNotNil] && [self.choiceProvince isNotNil]) {
        [[NetFuel setFuelDefaultSettingInfo:@{@"city":self.choiceProvince,@"fuelLabel":self.choiceFuelPriceModel.fuelLabel,@"commonCity":self.choiceCity}] requestSuccess:^(id JSON) {
            [wself initFuelDefault];
            if (success) success();
        } failure:^(id JSON) {
            [wself initFuelDefault];
            if (fail) fail();
        }];
    }
}

-(void)cancelResetDefault{
    [self initChoiceFuelInfo];
}

-(void)getFuelPriceSuccess:(void (^)(NSArray *))success fail:(void (^)())fail{
    if ([self.choiceCity isNotNil] && [self.choiceProvince isNotNil]) {

        [[NetFuel getFuelPricesWithProvice:self.choiceProvince city:self.choiceCity] requestSuccess:^(id JSON) {
            NSArray *tmp = JSON[@"info"];
            NSMutableArray *arr = [NSMutableArray arrayWithCapacity:4];
            NSInteger max = tmp.count;
            for (int i = 0; i < max; i++) {
                [arr addObject:[[FuelPriceModel alloc] initWithDic:tmp[i]]];
            }
            if (success) success(arr);
        } failure:^(id JSON) {
            if (fail) fail();
        }];
    }

}

-(NSString *)showChoiceCity{
    if (![self.choiceCity isNotNil] || ![self.choiceProvince isNotNil]) {
        return @"选择所在地";
    }else if ([self.choiceProvince isEqualToString:self.choiceCity]){
        return self.choiceProvince;
    }else{
        return [NSString stringWithFormat:@"%@ %@",self.choiceProvince,self.choiceCity];
    }
}

-(NSString *)choiceProvince{
    if (!_choiceProvince) {
        return @"";
    }
    return _choiceProvince;
}

-(NSString *)choiceCity{
    if (!_choiceCity) {
        return @"";
    }
    return _choiceCity;
}

-(NSMutableArray *)monthModels{
    if (!_monthModels) {
        _monthModels = [NSMutableArray arrayWithCapacity:7];
    }
    return _monthModels;
}

-(NSMutableDictionary *)fuelInfos{
    if (!_fuelInfos) {
        _fuelInfos = [NSMutableDictionary dictionaryWithCapacity:7];
    }
    return _fuelInfos;
}

#pragma mark -

-(NSArray *)months{
    return [self.monthModels copy];
}

-(DateModel *)leftmostMonth{
    if (!_leftmostMonth) {
        _leftmostMonth = [CALENDARMGR monthBeforeDateModel:USERINFO.bindingDay months:5];
    }
    return _leftmostMonth;
}

-(DateModel *)rightmostMonth{
    if (!_rightmostMonth) {
        _rightmostMonth = [CALENDARMGR monthAfterDateModel:CALENDARMGR.today month:5];
    }
    return _rightmostMonth;
}

#pragma mark - h5
-(NSArray *)years{
    if (!_years) {
        NSMutableArray *tmp = [NSMutableArray arrayWithCapacity:2];
        NSInteger year = USERINFO.bindingDay.year;
        while (year <= CALENDARMGR.today.year) {
            [tmp addObject:@(year)];
            year++;
        }
        _years = [tmp copy];
    }
    return _years;
}
-(NSInteger)choiceYear{
    if (!_choiceYear) {
        return CALENDARMGR.today.year;
    }
    return _choiceYear;
}
-(NSString *)h5Link{
    return [NSString stringWithFormat:@"http://r.ichezheng.com/h5/totaloil/index.html#/index?icz_uid=%zd&icz_key=%@&year=%zd",USERINFO.userID,USERINFO.iczkey,self.choiceYear];
}

@end
